package com.ja.openchat.ui.found;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.adapters.CircleHomeAdapter;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.views.BottomSheetBar;
import com.ja.openchat.views.ExLinearLayoutManager;
import com.ja.openchat.views.InputAwareLayout;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.circle.BlogReplyInfo;
import com.zy.openchat.core.model.circle.BlogReplysInfo;
import com.zy.openchat.core.model.circle.BlogUserInfo;
import com.zy.openchat.core.model.circle.InputBlogIdType;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.AndroidBug5497Workaround;
import com.zy.openchat.util.Common;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class CircleDetailActivity extends JaBaseActivity implements OnCircleRemarkListener{
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.rootLinearLayout)
    InputAwareLayout rootLinearLayout;
    private CircleHomeAdapter mAdapter;

    public static void startDetail(Context context,long blogId){
        startDetail(context,blogId,0);
    }

    public static void startDetail(Context context,long blogId,int type){
        Intent intent = new Intent(context,CircleDetailActivity.class);
        intent.putExtra("blogId",blogId);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }

    private BottomSheetBar mBottomSheetBar;

    private long mBlogId;
    private List<MultiItemEntity> mData = new ArrayList<>();
    @Override
    public void initData() {
        setTitle(getString(R.string.dynamic_details));
        AndroidBug5497Workaround.assistActivity(this);
        int type = 0;
        if(getIntent()!=null){
            mBlogId = getIntent().getLongExtra("blogId",0);
            type = getIntent().getIntExtra("type",0);
        }
        mAdapter = new CircleHomeAdapter(3,mData,viewModel);
        recyclerView.setItemAnimator(null);
        recyclerView.setLayoutManager(new ExLinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                try {
                    if(view.getId() !=  R.id.comment_btn){
                        mAdapter.onItemChildClick(adapter,view,position);
                    }

                    MultiItemEntity multiItemEntity = mAdapter.getItem(position);
                    if(multiItemEntity==null){
                        return;
                    }
                    switch (view.getId()){
                        case R.id.remark_et:
                        case R.id.comment_btn:
                            showRemarkBar(new InputBlogIdType(true,mBlogId),getString(R.string.comment_text),view);
                            break;
                        case R.id.delete_btn:
                            if(multiItemEntity instanceof BlogInfo){
                                BlogInfo blogInfo = (BlogInfo)multiItemEntity;
                                new XPopup.Builder(CircleDetailActivity.this).autoDismiss(true).asConfirm(
                                        getString(R.string.dialog_title_tip)
                                        , getString(R.string.delete_post_question)
                                        , getString(R.string.cancle_text)
                                        , getString(R.string.delete_text), new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        TelegramManager.getTelegramManager().deleteBlog(CircleDetailActivity.this, blogInfo.id, new TgResultBlock<TgResponse>() {
                                            @Override
                                            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                                                if(obj.ok){
                                                    ToastUtils.showShort(getString(R.string.successfully_deleted));
                                                    finish();
                                                }else{
                                                    ToastUtils.showShort(getString(R.string.request_error));
                                                }
                                            }

                                            @Override
                                            public void onTimeout(Map<String, Object> request) {
                                                ToastUtils.showShort(getString(R.string.request_error));
                                            }
                                        });
                                    }
                                }, new OnCancelListener() {
                                    @Override
                                    public void onCancel() {

                                    }
                                }, false).show();
                            }

                            break;
                        case R.id.remark_btn:
                            if(multiItemEntity instanceof BlogReplyInfo){
                                showRemarkBar(new InputBlogIdType(false,((BlogReplyInfo)multiItemEntity).id),getString(R.string.comment_text),(View) view.getParent());
                            }
                            break;
                    }
                }catch (Exception e){

                }
            }
        });
//        rootLinearLayout.addOnKeyboardHiddenListener(new KeyboardAwareLinearLayout.OnKeyboardHiddenListener() {
//            @Override
//            public void onKeyboardHidden() {
//                if(mBottomSheetBar!=null){
//                    mBottomSheetBar.dismiss();
//                }
//            }
//        });
        requestData(currentPage);

        if(type==1){
            recyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    showRemarkBar(new InputBlogIdType(true,mBlogId),getString(R.string.comment_text),null);
                }
            },500);
        }
    }


    private void refreshPage(){
        currentPage = 0;
        requestData(currentPage);
    }

    private int currentPage = 0;

    private void requestData(int page){
        if(page == 0){
            TelegramManager.getTelegramManager().getBlogInfo(this, mBlogId, new TgResultBlock<BlogInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, BlogInfo obj) {
                    mData.clear();
                    if(obj!=null){
                        mData.add(0,obj);
                    }
                    mAdapter.notifyDataSetChanged();
                    requestReplyInfo(page);
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }else{
            requestReplyInfo(page);
        }


    }

    private void requestReplyInfo(int page){
        TelegramManager.getTelegramManager().getBlogReplys(this, mBlogId, 20, page*20, new TgResultBlock<BlogReplysInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, BlogReplysInfo obj) {
                if(obj==null||Common.isEmpty(obj.replys)){
                    mAdapter.notifyDataSetChanged();
                    mAdapter.getLoadMoreModule().loadMoreEnd();
                }else{
                    mData.addAll(obj.replys);
                    mAdapter.notifyDataSetChanged();
                    mAdapter.getLoadMoreModule().loadMoreComplete();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                mAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
    }


    private void parrelChildReplys(){

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mBottomSheetBar!=null){
            mBottomSheetBar.destory();
            mBottomSheetBar.dismiss();
        }
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_circle_detail;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void showRemarkBar(InputBlogIdType blogIdType,String hint, View view){
        if(mBottomSheetBar==null){
            mBottomSheetBar = BottomSheetBar.delegation(this,rootLinearLayout);
            mBottomSheetBar.setCallback(new BottomSheetBar.OnBottomCallback() {
                @Override
                public void onShow(int[] inputViewCoordinatesOnScreen) {
                    recyclerView.smoothScrollBy(0,inputViewCoordinatesOnScreen[1],new LinearInterpolator());
                }

                @Override
                public void onClickSend(InputBlogIdType targetId, String content) {
                    showProgress();
                    TelegramManager.getTelegramManager().commentBlog(CircleDetailActivity.this, targetId, content, new TgResultBlock<TgResponse>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                            hideProgress();
                            if(obj!=null){
                                if(obj.ok){
                                    mBottomSheetBar.clean();
                                    refreshPage();
                                }else{
                                    showErrorTip(obj.errString);
                                }
                            }else{
                                showErrorTip(getString(R.string.request_error));
                            }
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                            hideProgress();
                            showErrorTip(getString(R.string.request_error));
                        }
                    });
                }
            });
        }
        mBottomSheetBar.setTargetId(blogIdType);
        mBottomSheetBar.show(hint,view);
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Override
    public void onTgEvent(TgEvent tg_event) {
        if (tg_event == null) {
            return;
        }
        switch (tg_event.event) {
            case ECircle_Follow_Update:
                if(tg_event.data!=null&&tg_event.data instanceof BlogUserInfo){
                    BlogUserInfo blogUserInfo = (BlogUserInfo) tg_event.data;
                    mAdapter.updateBlogUserInfo(blogUserInfo);
                }
                break;
            case ECircle_Like_Update:
                if(tg_event.data!=null){
                    if(tg_event.data instanceof BlogReplyInfo){
                        BlogReplyInfo blogReplyInfo = (BlogReplyInfo) tg_event.data;
                        ((CircleHomeAdapter)mAdapter).notifyLike(blogReplyInfo);
                    }else if(tg_event.data instanceof BlogInfo){
                        BlogInfo blogInfo = (BlogInfo) tg_event.data;
                        ((CircleHomeAdapter)mAdapter).notifyLike(blogInfo);
                    }

                }
                break;
            case EUser_Td_Contact_Photo_Ok:
            case EUser_Td_UpdateContactInfo:
                if ((tg_event.data instanceof UserInfo)) {
                    UserInfo userInfo = (UserInfo) tg_event.data;
                    Observable.create(new ObservableOnSubscribe<DiffUtil.DiffResult>() {
                        @Override
                        public void subscribe(ObservableEmitter<DiffUtil.DiffResult> e) {
                            DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new BlogAvatarDiffCallBack(mAdapter.getData(), mAdapter.getData()), false);
                            e.onNext(diffResult);
                        }
                    }).subscribeOn(Schedulers.computation())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<DiffUtil.DiffResult>() {
                                @Override
                                public void accept(DiffUtil.DiffResult diffResult) {
                                    diffResult.dispatchUpdatesTo(mAdapter);
                                }
                            });
                }
                break;
            case EUser_Td_Message_Photo_Ok:
            case EUser_Td_Message_Video_Ok:
                if(tg_event.data instanceof FileTaskInfo &&tg_event.dataEx instanceof FileInfo) {
                    FileInfo fileInfo = (FileInfo) tg_event.dataEx;
                    String ids = ((FileTaskInfo) tg_event.data).id;
                    if (!TextUtils.isEmpty(ids) && ids.contains("_")) {
                        String[] idArray = ids.split("_");
                        if (idArray.length > 1&&idArray[1].equals(mBlogId)&&mAdapter.getItemCount()>0) {
                            MultiItemEntity multiItemEntity = mAdapter.getItem(0);
                            if(multiItemEntity!=null&&multiItemEntity instanceof BlogInfo){
                                BlogInfo blogInfo = (BlogInfo) multiItemEntity;
                                if(idArray[1].equals(blogInfo.id)){
                                    switch (tg_event.event) {
                                        case EUser_Td_Message_Photo_Ok:
                                            blogInfo.updatePhotoFile(fileInfo);
                                            break;
                                        case EUser_Td_Message_Video_Ok:
                                            blogInfo.updateVideoFile(fileInfo);
                                            break;
                                    }
                                    mAdapter.notifyItemChanged(0);
                                    break;
                                }
                            }
                        }
                    }
                }
                break;
        }
    }
}
